package ird.demo.controller.transaction;

import ird.demo.bo.AjaxResult;
import ird.demo.common.DemoConstant;
import ird.demo.domain.IrdSystem;
import ird.demo.domain.Transaction;
import ird.demo.service.IrdSystemService;
import ird.demo.service.TranService;

import java.security.Principal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/transaction/IRSM0002")
public class IRSM0002Controller extends TranController {
	
	@Autowired
	private TranService tranSvc;
	
	@Autowired
	private IrdSystemService irdSysSvc;
	
	@Override
	protected String getTc() {
		return "IRSM0002";
	}

	@Override
	protected void preInput(ModelMap model) {
//		List<Menu> menuList = service.findAllMenu();
//		model.addAttribute("menuList", menuList);
		
	}
	
	@Override
	protected void preDetail(HttpServletRequest request, HttpSession session, ModelMap model) {
		String act = request.getParameter("act");
		System.out.println("act="+act);
		model.addAttribute("act", act);
		String actDesc = null;
		
		Map<String,String> keyParam = new HashMap<String,String>();
		if("add".equals(act)){
			actDesc = "Add Transaction";
			keyParam.put("act", "add");
			List<Transaction> allTranList = tranSvc.findAllTran();
			List<Transaction> tranKeyValuList = new ArrayList<Transaction>();
			
			for(Transaction tmpTran: allTranList){
				Transaction tranKeyValue = new Transaction();
				tranKeyValue.setTranId(tmpTran.getTranId());
				tranKeyValue.setTranDesc(tmpTran.getTranDesc());
				tranKeyValuList.add(tranKeyValue);
			}
			System.out.println("tranKeyValuList="+tranKeyValuList);
			
			model.addAttribute("actDesc", actDesc);
			model.addAttribute("tranKeyValuList", gson.toJson(tranKeyValuList));
		}
		else if ("upd".equals(act)){
			actDesc = "Modify Transaction";
			
			String tranId = request.getParameter("tranId");
			String rowIdx = request.getParameter("rowIdx");
			String page = request.getParameter("page");
			String rows = request.getParameter("rows");
			
			keyParam.put("act", "upd");
			keyParam.put("tranId", tranId);
			keyParam.put("rowIdx", rowIdx);
			keyParam.put("page", page);
			keyParam.put("rows", rows);
			session.setAttribute(DemoConstant.KEY_PARAM, keyParam);
			
			System.out.println("tranId"+tranId);
			System.out.println("rowIdx"+rowIdx);
			System.out.println("page"+page);
			System.out.println("rows"+rows);
			
			Transaction tran = tranSvc.findTranById(tranId);
			
			List<Transaction> allTranList = tranSvc.findAllTran();
			List<Transaction> tranKeyValuList = new ArrayList<Transaction>();
			
			for(Transaction tmpTran: allTranList){
				if(tmpTran.getTranId().equals(tranId) == false){
					Transaction tranKeyValue = new Transaction();
					tranKeyValue.setTranId(tmpTran.getTranId());
					tranKeyValue.setTranDesc(tmpTran.getTranDesc());
					tranKeyValuList.add(tranKeyValue);
				}
			}
			System.out.println("tranKeyValuList="+tranKeyValuList);
			
			model.addAttribute("actDesc", actDesc);
			model.addAttribute("tranBean", tran);
			model.addAttribute("tranKeyValuList", gson.toJson(tranKeyValuList));
		}
		//'del' will delete directly then jump to done screen(skip detail screen)
		else if ("del".equals(act)){
			System.out.println("tranIds"+request.getParameter("tranIds"));
			String[] tranIdArr = request.getParameter("tranIds").split(",");
			for(String tranId : tranIdArr){
				System.out.println("delete tran["+tranId+"]");
				tranSvc.delTran(tranId);
			}
			String redirectUrl = done(request, session, model);
			model.addAttribute(DemoConstant.REDIRECT_UTL, redirectUrl);
		}
		
		session.setAttribute(DemoConstant.KEY_PARAM, keyParam);
	}
	
	@RequestMapping("/getTranListPage")
	@ResponseBody
	public String getTranListPage(
			@RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) String order,
            Model model){
		System.out.println("BaseController.list, page="+page+",rows="+rows+",sort="+sort+",order="+order);
		int pageNum = page==null?1:page-1;
		int rowNum = rows==null?DemoConstant.PAGE_SIZE:rows;
		String sortStr = sort==null?"tranId":sort;
		Direction orderDirect = DemoConstant.DESC.equalsIgnoreCase(order)?Direction.DESC:Direction.ASC;
		
		PageRequest pgReq = new PageRequest(pageNum, rowNum, orderDirect, sortStr);
		System.out.println("request="+gson.toJson(pgReq));
		Page<Transaction> tranPage = tranSvc.findPageTran(pgReq);
		model.addAttribute(DemoConstant.ROWS, tranPage.getContent());
		model.addAttribute(DemoConstant.TOTAL, tranPage.getTotalElements());
		return gson.toJson(model);
	}
	

	@RequestMapping(value="/validAndUpd/{act}", method = RequestMethod.POST)
	@ResponseBody
	public String validAndUpd(@RequestBody Transaction tran, @PathVariable("act") String act, Principal principal){
		System.out.println("==========validAndUpd");
		
		AjaxResult result = null;
		
		tran.setUpdateBy(principal.getName());
		tran.setUpdateTs(new Timestamp(new Date().getTime()));
		try{
			System.out.println("==========before update,act="+act);
			if("add".equals(act)){
				Transaction existedTran = tranSvc.findTranById(tran.getTranId());
				System.out.println("check before add tran:"+existedTran);
				if(existedTran != null){
					String errMsg = messageSource.getMessage("IRSM0002.add.tranExisted", null, Locale.getDefault());
					result = new AjaxResult(DemoConstant.FAIL, "tranId", errMsg);
					return gson.toJson(result);
				}
				
			}
			tranSvc.saveTran(tran);
		}
		catch(Exception e){
			e.printStackTrace();
			String errMsg = messageSource.getMessage("system.genericErr", null, Locale.getDefault());
			result = new AjaxResult(DemoConstant.FAIL, "", errMsg);
			return gson.toJson(result);
		}
		
		result = new AjaxResult(DemoConstant.SUCCESS, null, null);
		return gson.toJson(result);
	}

	@RequestMapping("/getIrdSysList")
	@ResponseBody
	public String getIrdSysList(Model model){
		List<IrdSystem> irdSysList = irdSysSvc.findAllIrdSys();
		model.addAttribute("irdSysList", irdSysList);
		return gson.toJson(irdSysList);
	}
}
